<template>
  <div class="register-debug">
    <div class="debug-container">
      <el-card class="debug-card">
        <template #header>
          <div class="card-header">
            <span>注册API调试工具</span>
            <el-tag type="warning">调试模式</el-tag>
          </div>
        </template>

        <div class="debug-content">
          <div class="step-section">
            <h3>步骤1: 发送验证码</h3>
            <div class="step-form">
              <el-form :model="codeForm" label-width="100px">
                <el-form-item label="邮箱地址">
                  <el-input
                    v-model="codeForm.email"
                    placeholder="请输入QQ邮箱"
                    style="width: 300px;"
                  />
                  <el-button
                    type="primary"
                    @click="sendCode"
                    :loading="sendingCode"
                    style="margin-left: 10px;"
                  >
                    发送验证码
                  </el-button>
                </el-form-item>
              </el-form>
              
              <div v-if="codeResult" class="result-display">
                <h4>发送结果:</h4>
                <pre class="json-display">{{ JSON.stringify(codeResult, null, 2) }}</pre>
              </div>
            </div>
          </div>

          <el-divider />

          <div class="step-section">
            <h3>步骤2: 用户注册</h3>
            <div class="step-form">
              <el-form :model="registerForm" label-width="100px">
                <el-form-item label="用户名">
                  <el-input v-model="registerForm.username" placeholder="用户名" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="registerForm.email" placeholder="邮箱" />
                </el-form-item>
                <el-form-item label="密码">
                  <el-input v-model="registerForm.password" placeholder="密码" show-password />
                </el-form-item>
                <el-form-item label="确认密码">
                  <el-input v-model="registerForm.confirmPassword" placeholder="确认密码" show-password />
                </el-form-item>
                <el-form-item label="验证码">
                  <el-input v-model="registerForm.verificationCode" placeholder="验证码" />
                </el-form-item>
                <el-form-item>
                  <el-button type="success" @click="register" :loading="registering">
                    注册用户
                  </el-button>
                  <el-button @click="fillTestData">填充测试数据</el-button>
                  <el-button @click="copyFromStep1">从步骤1复制邮箱</el-button>
                </el-form-item>
              </el-form>
              
              <div v-if="registerResult" class="result-display">
                <h4>注册结果:</h4>
                <pre class="json-display">{{ JSON.stringify(registerResult, null, 2) }}</pre>
              </div>
            </div>
          </div>

          <el-divider />

          <div class="debug-info">
            <h3>调试信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <h4>发送验证码API</h4>
                <p><strong>接口:</strong> POST /user/sendRegisterCode</p>
                <p><strong>参数:</strong> { email: string }</p>
              </div>
              <div class="info-item">
                <h4>用户注册API</h4>
                <p><strong>接口:</strong> POST /user/register</p>
                <p><strong>参数:</strong></p>
                <pre class="api-params">{
  "username": "string",
  "email": "string", 
  "password": "string",
  "confirmPassword": "string",
  "verificationCode": "string"
}</pre>
              </div>
            </div>
          </div>

          <div class="request-logs">
            <h3>请求日志</h3>
            <div class="logs-container">
              <div v-for="(log, index) in requestLogs" :key="index" class="log-item">
                <div class="log-header">
                  <span class="log-time">{{ log.time }}</span>
                  <el-tag :type="log.success ? 'success' : 'danger'">
                    {{ log.type }}
                  </el-tag>
                </div>
                <div class="log-content">
                  <p><strong>请求:</strong></p>
                  <pre>{{ JSON.stringify(log.request, null, 2) }}</pre>
                  <p><strong>响应:</strong></p>
                  <pre>{{ JSON.stringify(log.response, null, 2) }}</pre>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { sendRegisterCode, userRegister } from '@/utils/apiService'

// 响应式数据
const sendingCode = ref(false)
const registering = ref(false)
const codeResult = ref(null)
const registerResult = ref(null)
const requestLogs = ref([])

const codeForm = reactive({
  email: ''
})

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  verificationCode: ''
})

// 方法
const addLog = (type, request, response, success) => {
  requestLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    type,
    request,
    response,
    success
  })
  
  // 只保留最近10条日志
  if (requestLogs.value.length > 10) {
    requestLogs.value = requestLogs.value.slice(0, 10)
  }
}

const sendCode = async () => {
  if (!codeForm.email) {
    ElMessage.warning('请输入邮箱地址')
    return
  }

  sendingCode.value = true
  codeResult.value = null

  try {
    console.log('发送验证码请求:', { email: codeForm.email })
    
    const response = await sendRegisterCode(codeForm.email)

    console.log('🔍 验证码发送响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    codeResult.value = responseData
    addLog('发送验证码', { email: codeForm.email }, responseData, responseData.code === 200 || responseData.code === '200')

    if (responseData.code === 200 || responseData.code === '200') {
      ElMessage.success('验证码发送成功')
    } else {
      ElMessage.error(responseData.message || '验证码发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    const errorResponse = {
      error: error.message,
      status: error.response?.status,
      data: error.response?.data
    }
    codeResult.value = errorResponse
    addLog('发送验证码', { email: codeForm.email }, errorResponse, false)
    ElMessage.error('验证码发送失败')
  } finally {
    sendingCode.value = false
  }
}

const register = async () => {
  if (!registerForm.username || !registerForm.email || !registerForm.password || 
      !registerForm.confirmPassword || !registerForm.verificationCode) {
    ElMessage.warning('请填写完整的注册信息')
    return
  }

  registering.value = true
  registerResult.value = null

  try {
    const requestData = {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      confirmPassword: registerForm.confirmPassword,
      verificationCode: registerForm.verificationCode
    }
    
    console.log('注册请求:', requestData)
    
    const response = await userRegister(requestData)
    
    registerResult.value = response
    addLog('用户注册', requestData, response, response.code === '200')
    
    if (response.code === '200') {
      ElMessage.success('注册成功')
    } else {
      ElMessage.error(response.message || '注册失败')
    }
  } catch (error) {
    console.error('注册失败:', error)
    const errorResponse = {
      error: error.message,
      status: error.response?.status,
      data: error.response?.data
    }
    registerResult.value = errorResponse
    addLog('用户注册', registerForm, errorResponse, false)
    ElMessage.error('注册失败')
  } finally {
    registering.value = false
  }
}

const fillTestData = () => {
  const timestamp = Date.now().toString().slice(-6)
  registerForm.username = `testuser${timestamp}`
  registerForm.email = `${timestamp}@qq.com`
  registerForm.password = 'Test123!@#'
  registerForm.confirmPassword = 'Test123!@#'
  registerForm.verificationCode = '123456'
  
  ElMessage.success('测试数据已填充')
}

const copyFromStep1 = () => {
  if (codeForm.email) {
    registerForm.email = codeForm.email
    ElMessage.success('邮箱已复制')
  } else {
    ElMessage.warning('请先在步骤1中输入邮箱')
  }
}
</script>

<style scoped>
.register-debug {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.debug-container {
  max-width: 1000px;
  margin: 0 auto;
}

.debug-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #2c3e50;
}

.debug-content {
  padding: 20px 0;
}

.step-section {
  margin-bottom: 30px;
}

.step-section h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.step-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.result-display {
  margin-top: 20px;
}

.result-display h4 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.json-display {
  background: #2c3e50;
  color: #fff;
  padding: 15px;
  border-radius: 6px;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
}

.debug-info h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.info-item {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.info-item h4 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.info-item p {
  margin: 5px 0;
  color: #606266;
}

.api-params {
  background: #2c3e50;
  color: #fff;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 5px;
}

.request-logs h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.logs-container {
  max-height: 400px;
  overflow-y: auto;
}

.log-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.log-time {
  font-size: 12px;
  color: #909399;
}

.log-content p {
  margin: 10px 0 5px 0;
  font-weight: 500;
  color: #2c3e50;
}

.log-content pre {
  background: #2c3e50;
  color: #fff;
  padding: 10px;
  border-radius: 4px;
  font-size: 11px;
  max-height: 150px;
  overflow-y: auto;
  white-space: pre-wrap;
}
</style>
